<template>
  <div class="post-detail-container">
    <div class="post-detail" v-loading="loading">
      <!-- 返回链接 -->
      <div class="back-link">
        <router-link to="/forum">
          <i class="el-icon-arrow-left"></i> 返回论坛
        </router-link>
      </div>

      <!-- 帖子内容 -->
      <div v-if="post" class="post-content">
        <h1 class="post-title">{{ post.title }}</h1>
        
        <div class="post-meta">
          <div class="author-info">
            <img :src="post.avatar" :alt="post.screenName" class="author-avatar">
            <div class="author-details">
              <div class="author-name">{{ post.screenName || post.userName }}</div>
              <div class="publish-time">发布于 {{ formatDate(post.createTime) }}</div>
            </div>
          </div>
          <div class="post-stats">
            <span class="views"><i class="el-icon-view"></i> {{ post.views || 0 }}</span>
            <span class="comments"><i class="el-icon-chat-dot-round"></i> {{ post.comments || 0 }}</span>
            <span class="likes" :class="{ 'is-liked': post.isLiked }" @click="toggleLike">
              <i :class="post.isLiked ? 'fas fa-heart' : 'far fa-heart'"></i> {{ post.likes || 0 }}
            </span>
          </div>
        </div>

        <!-- 帖子信息卡片
        <div class="post-info-card">
          <div class="post-tags" v-if="post.topicName">
            <span class="post-topic">
              <i class="el-icon-collection-tag"></i> 
              <el-tag size="small" type="info">{{ post.topicName }}</el-tag>
            </span>
            <span class="post-type" v-if="post.mediaType && post.mediaType !== '0'">
              <i class="el-icon-picture" v-if="post.mediaType === '1'"></i>
              <i class="el-icon-video-camera" v-if="post.mediaType === '2'"></i>
              <i class="el-icon-headset" v-if="post.mediaType === '3'"></i>
              <el-tag size="small" type="primary">
                {{ post.mediaType === '1' ? '图片' : post.mediaType === '2' ? '视频' : '音频' }}
              </el-tag>
            </span>
          </div>
        </div> -->

        <!-- 文字内容 -->
        <div class="post-body">
          <p v-html="formatContent(post.content)"></p>
        </div>

        <!-- 媒体内容 -->
        <div v-if="post.mediaType === '1' && post.mediaUrl" class="post-media">
          <div class="media-container">
            <img :src="post.mediaUrl" class="media-image" alt="帖子图片">
          </div>
        </div>
        <div v-if="post.mediaType === '2' && post.mediaUrl" class="post-media">
          <div class="video-container">
            <video controls :src="post.mediaUrl" class="post-video"></video>
          </div>
        </div>
        <div v-else-if="post.mediaType === '3' && post.mediaUrl" class="post-media">
          <div class="audio-container">
            <audio controls :src="post.mediaUrl" class="post-audio"></audio>
          </div>
        </div>
        
        <!-- 帖子操作
        <div class="post-actions">
          <el-button type="primary" plain size="small" @click="scrollToComment">
            <i class="el-icon-chat-dot-round"></i> 参与讨论
          </el-button>
          <el-button v-if="canEdit" type="warning" plain size="small" @click="editPost">
            <i class="el-icon-edit"></i> 编辑
          </el-button>
        </div> -->
      </div>

      <!-- 评论区 -->
      <div class="comment-section" ref="commentSection">
        <h3 class="section-title">评论区 ({{post.comments || 0}})</h3>
        
        <!-- 评论表单 -->
        <div class="comment-form">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="参与讨论..."
            v-model="commentContent"
            maxlength="500"
            show-word-limit
          ></el-input>
          <div class="form-actions">
            <el-button type="primary" :disabled="!commentContent.trim() || submitting" @click="submitComment">
              <i class="el-icon-s-promotion"></i> 发表评论
            </el-button>
          </div>
        </div>

        <!-- 评论列表 -->
        <div v-loading="commentLoading" class="comment-list">
          <div v-if="comments.length > 0" class="comments-container">
            <div v-for="comment in comments" :key="comment.commentId" class="comment-item" :data-id="comment.commentId" @click.stop>
              <div class="comment-avatar">
                <img :src="comment.avatar">
              </div>
              <div class="comment-content">
                <div class="comment-header">
                  <span class="comment-author">{{ comment.screenName }}</span>
                  <span class="comment-date">{{ formatDate(comment.createTime) }}</span>
                </div>
                <div class="comment-text" v-html="formatContent(comment.content)"></div>
                <div class="comment-actions">
                  <span class="comment-like" :class="{ 'liked': comment.isLiked }" @click.stop="toggleCommentLike(comment)">
                    <i :class="comment.isLiked ? 'fas fa-heart' : 'far fa-heart'"></i>
                    <span>{{ comment.likes || 0 }}</span>
                  </span>
                  <span class="comment-reply" @click.stop="replyToComment(comment)">
                    <i class="far fa-comment"></i> 回复
                  </span>
                  <span v-if="currentUserId === comment.userId" class="comment-delete" @click.stop="deleteComment(comment)">
                    <i class="far fa-trash-alt"></i> 删除
                  </span>
                </div>

                <!-- 回复区域 -->
                <div v-if="replyingTo === comment.commentId" class="reply-form" @click.stop>
                  <el-input
                    type="textarea"
                    :rows="3"
                    :placeholder="'请输入回复评论...'"
                    v-model="replyContent"
                    maxlength="300"
                    show-word-limit
                  ></el-input>
                  <div class="form-actions">
                    <el-button size="small" @click.stop="cancelReply">取消</el-button>
                    <el-button size="small" type="primary" :disabled="!replyContent.trim() || submitting" @click.stop="submitReply(comment)">回复</el-button>
                  </div>
                </div>

                <!-- 子评论折叠按钮 -->
                <div v-if="comment.replies && comment.replies.length > 0" class="comment-replies-container">
                  <div class="replies-toggle" @click.stop="toggleCommentReplies(comment, $event)">
                    <i :class="comment.showReplies ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i>
                    {{ comment.showReplies ? '收起回复' : '显示回复' }} ({{ comment.replies.length }})
                  </div>
                  <div v-if="comment.showReplies" class="comment-replies" @click.stop>
                    <div v-for="reply in comment.replies" :key="reply.id" class="reply-item" @click.stop>
                      <div class="reply-avatar">
                        <img :src="reply.avatar || '/images/default-avatar.png'" :alt="reply.userName">
                      </div>
                      <div class="reply-content">
                        <div class="reply-header">
                          <span class="reply-author">{{ reply.screenName }}</span>
                          <span class="reply-target" v-if="reply.replyToUserName">回复 {{ reply.replyToUserName }}</span>
                          <span class="reply-date">{{ formatDate(reply.createTime) }}</span>
                        </div>
                        <div class="reply-text" v-html="formatContent(reply.content)"></div>
                        <div class="reply-actions">
                          <span class="reply-like" :class="{ 'liked': reply.isLiked }" @click.stop="toggleReplyLike(reply)">
                            <i :class="reply.isLiked ? 'fas fa-heart' : 'far fa-heart'"></i>
                            <span>{{ reply.likes || 0 }}</span>
                          </span>
                          <span v-if="currentUserId === reply.userId" class="reply-delete" @click.stop="deleteReply(comment, reply)">
                            <i class="far fa-trash-alt"></i> 删除
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 暂无评论 -->
          <div v-else-if="!commentLoading" class="no-comments">
            <i class="el-icon-chat-dot-square"></i>
            <p>暂无评论，快来发表第一条评论吧！</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import service from '@/utils/request'
// 引入 FontAwesome 样式
import '@fortawesome/fontawesome-free/css/all.css'
import Vue from 'vue'
// 引入侮辱性词汇检测工具
import { containsInsultingWords } from '@/utils/insultingWords'

export default {
  name: 'PostDetailVue',
  data() {
    return {
      loading: true,
      postId: null,
      post: null,
      comments: [],
      commentContent: '',
      replyingTo: null,
      replyToUserId: null,
      replyContent: '',
      canEdit: false,
      submitting: false,
      commentLoading: false,
      userLikes: [], // 存储用户的点赞记录
      currentUserId: '' // 移除从localStorage获取，改为从后端获取
    }
  },
  created() {
    this.postId = this.$route.params.id
    this.addViews()
    this.getCurrentUserId() // 添加获取当前用户ID的方法调用

    setTimeout(() => {
      this.getPostDetail();
      this.getComments();
      this.getUserLikes(); // 获取用户点赞记录
    }, 1000);
  },
  methods: {
    addViews() {
      service.put(`/api/forum/post/addViews/${this.postId}`).then(res => {
        console.log(res)
      }).catch(err => {
        console.error('更新浏览量失败:', err)
      })
    },
    // 获取帖子详情
    getPostDetail() {
      this.loading = true
      service.get(`/api/forum/post/detail/${this.postId}`).then(res => {
        this.loading = false
        if (res.code === 200 && res.data) {
          this.post = res.data
          
          // 确保post对象有isLiked属性
          this.$set(this.post, 'isLiked', false)
          
          document.title = `${this.post.title} - 京剧艺术论坛`
          
          // 检查当前用户是否为作者，使用从后端获取的用户ID
          this.canEdit = this.currentUserId && this.currentUserId === this.post.userId
          
          // 如果已经获取到用户点赞数据，立即更新帖子点赞状态
          if (this.userLikes.length > 0) {
            this.updatePostLikeStatus()
          }
        } else {
          this.$message.error(res.message || '帖子不存在或已被删除')
          this.$router.push('/forum')
        }
      }).catch(err => {
        this.loading = false
        console.error('获取帖子详情失败:', err)
        this.$message.error('获取帖子详情失败，请稍后重试')

        // 3秒后自动重试一次
        setTimeout(() => {
          if (!this.post) {
            this.getPostDetail()
          }
        }, 3000)
      })
    },
    
    // 获取评论列表
    getComments() {
      this.commentLoading = true
      const token = localStorage.getItem('token')
      
      // 请求参数添加token
      const params = token ? { token } : {}
      
      service.get(`/api/forum/comment/getComments/${this.postId}`, { params }).then(res => {
        this.commentLoading = false
        if (res.code === 200 && res.data) {
          console.log(res.data)
          
          // 对评论按时间排序，最新的排在前面
          const sortedComments = res.data || []
          sortedComments.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
          
          // 对每个评论的回复也按时间排序并初始化折叠状态
          sortedComments.forEach(comment => {
            // 确保评论对象有所需的属性，避免undefined错误
            if (!comment.likes) comment.likes = 0
            this.$set(comment, 'isLiked', false) // 设置默认点赞状态为false
            if (!comment.avatar) comment.avatar = '/images/default-avatar.png'
            
            // 添加显示/隐藏回复的属性
            Vue.set(comment, 'showReplies', false)
            
            if (comment.replies && comment.replies.length > 0) {
              comment.replies.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
              
              // 确保每个回复都有必要的默认值
              comment.replies.forEach(reply => {
                if (!reply.likes) reply.likes = 0
                this.$set(reply, 'isLiked', false) // 设置默认点赞状态为false
                if (!reply.avatar) reply.avatar = '/images/default-avatar.png'
              })
            } else {
              // 确保replies是数组，避免模板中的v-if出错
              comment.replies = []
            }
          })
          
          this.comments = sortedComments
          
          // 如果已有用户点赞数据，更新评论的点赞状态
          if (this.userLikes.length > 0) {
            this.updateCommentsLikeStatus()
          }
        } else {
          console.warn('获取评论列表返回异常:', res)
          this.comments = []
        }
      }).catch(err => {
        this.commentLoading = false
        console.error('获取评论失败:', err)
        this.$message.error('获取评论失败，请稍后重试')
        this.comments = []
      })
    },
    
    // 获取用户的点赞记录
    getUserLikes() {
      const token = localStorage.getItem('token')
      if (!token) return

      service.get('/api/forum/like/getLikesList', {
        params: { token }
      }).then(res => {
        if (res.code === 200 && res.data) {
          this.userLikes = res.data || []
          
          // 更新帖子的点赞状态
          this.updatePostLikeStatus()
          
          // 更新评论的点赞状态
          this.updateCommentsLikeStatus()
        }
      }).catch(err => {
        console.error('获取用户点赞数据失败:', err)
      })
    },
    
    // 更新帖子的点赞状态
    updatePostLikeStatus() {
      if (this.post && this.userLikes.length > 0) {
        // 查找是否有对该帖子的点赞
        const isLiked = this.userLikes.some(like => 
          like.targetId === this.postId && like.targetType === 'POST'
        )
        
        // 使用Vue.set确保响应式更新
        this.$set(this.post, 'isLiked', isLiked)
      }
    },
    
    // 更新评论的点赞状态
    updateCommentsLikeStatus() {
      if (this.comments.length > 0 && this.userLikes.length > 0) {
        this.comments.forEach(comment => {
          // 检查评论是否被点赞
          const isCommentLiked = this.userLikes.some(like => 
            like.targetId === comment.commentId && like.targetType === 'COMMENT'
          )
          
          // 更新评论的点赞状态
          this.$set(comment, 'isLiked', isCommentLiked)
          
          // 检查评论的回复是否被点赞
          if (comment.replies && comment.replies.length > 0) {
            comment.replies.forEach(reply => {
              const isReplyLiked = this.userLikes.some(like => 
                like.targetId === reply.id && like.targetType === 'REPLY'
              )
              
              // 更新回复的点赞状态
              this.$set(reply, 'isLiked', isReplyLiked)
            })
          }
        })
      }
    },
    
    // 切换点赞状态
    toggleLike() {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再点赞')
        return
      }
      
      // 避免重复点击
      if (this.submitting) return
      this.submitting = true
      
      // 准备请求数据
      const likeData = {
        targetId: this.postId,
        token: localStorage.getItem('token'),
        targetType: 'POST' // 点赞的是帖子
      }
      
      const action = this.post.isLiked ? 'unlike' : 'like'
      
      service.post(`/api/forum/like/${action}`, likeData)
      .then(res => {
        if (res.code === 200) {
          // 更新点赞状态
          this.post.isLiked = !this.post.isLiked
          
          // 更新点赞数
          if (this.post.isLiked) {
            this.post.likes = (this.post.likes || 0) + 1
            
            // 添加到本地点赞记录
            if (res.data && res.data.likeId) {
              this.userLikes.push({
                likeId: res.data.likeId,
                targetId: this.postId,
                targetType: 'POST',
                userId: this.currentUserId // 使用后端获取的当前用户ID
              })
            }
          } else {
            this.post.likes = Math.max(0, (this.post.likes || 0) - 1)
            
            // 从本地点赞记录中移除
            const index = this.userLikes.findIndex(like => 
              like.targetId === this.postId && like.targetType === 'POST'
            )
            if (index !== -1) {
              this.userLikes.splice(index, 1)
            }
          }
        } else {
          this.$message.error(res.message || '操作失败')
        }
        this.submitting = false
      }).catch(err => {
        console.error('操作点赞失败:', err)
        this.$message.error('操作失败，请稍后重试')
        this.submitting = false
      })
    },
    
    // 提交评论
    submitComment() {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再评论')
        return
      }
      
      if (!this.commentContent.trim()) {
        this.$message.warning('评论内容不能为空')
        return
      }
      
      // 检查是否包含侮辱性词汇
      if (this.containsInsultingWords(this.commentContent)) {
        this.$message.error('评论内容包含侮辱性词汇，请文明发言')
        return
      }
      
      const comment = {
        postId: this.postId,
        token: localStorage.getItem('token'),
        content: this.commentContent.trim()
      }
      
      this.submitting = true
      
      service.post('/api/forum/comment/addComment', comment).then(res => {
        if (res.code === 200) {
          this.$message.success('评论成功')
          this.commentContent = ''
          // 重新加载评论
          this.getComments()
          
          // 更新评论数
          if (this.post) {
            this.post.comments = (this.post.comments || 0) + 1
          }
          
          // 滚动到评论列表顶部
          this.$nextTick(() => {
            const commentList = document.querySelector('.comment-list')
            if (commentList) {
              commentList.scrollIntoView({ behavior: 'smooth', block: 'start' })
            }
          })
        } else {
          this.$message.error(res.message || '评论失败')
        }
        this.submitting = false
      }).catch(err => {
        console.error('提交评论失败:', err)
        this.$message.error('评论失败，请稍后重试')
        this.submitting = false
      })
    },
    
    // 点赞评论
    toggleCommentLike(comment) {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再点赞')
        return
      }
      
      // 避免重复点击
      if (this.submitting) return
      this.submitting = true
      
      // 根据当前点赞状态决定操作
      const isLiked = comment.isLiked
      const action = isLiked ? 'unlike' : 'like'
      
      // 准备请求数据
      const likeData = {
        targetId: comment.commentId,
        token: localStorage.getItem('token'),
        targetType: 'COMMENT' // 点赞的是评论
      }
      
      service.post(`/api/forum/like/${action}`, likeData).then(res => {
        if (res.code === 200) {
          // 更新点赞状态
          comment.isLiked = !comment.isLiked
          
          // 更新点赞数
          if (comment.isLiked) {
            comment.likes = (comment.likes || 0) + 1
            
            // 添加到本地点赞记录
            if (res.data && res.data.likeId) {
              this.userLikes.push({
                likeId: res.data.likeId,
                targetId: comment.commentId,
                targetType: 'COMMENT',
                userId: this.currentUserId // 使用后端获取的当前用户ID
              })
            }
          } else {
            comment.likes = Math.max(0, (comment.likes || 0) - 1)
            
            // 从本地点赞记录中移除
            const index = this.userLikes.findIndex(like => 
              like.targetId === comment.commentId && like.targetType === 'COMMENT'
            )
            if (index !== -1) {
              this.userLikes.splice(index, 1)
            }
          }
        } else {
          this.$message.error(res.message || '操作失败')
        }
        this.submitting = false
      }).catch(err => {
        console.error('操作评论点赞失败:', err)
        this.$message.error('操作失败，请稍后重试')
        this.submitting = false
      })
    },
    
    // 点赞回复
    toggleReplyLike(reply) {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再点赞')
        return
      }
      
      // 避免重复点击
      if (this.submitting) return
      this.submitting = true
      
      const action = reply.isLiked ? 'unlike' : 'like'
      
      // 准备请求数据
      const likeData = {
        targetId: reply.commentId,
        token: localStorage.getItem('token'),
        targetType: 'REPLY' // 点赞的是回复
      }
      
      service.post(`/api/forum/like/${action}`, likeData).then(res => {
        if (res.code === 200) {
          // 更新点赞状态
          reply.isLiked = !reply.isLiked
          
          // 更新点赞数
          if (reply.isLiked) {
            reply.likes = (reply.likes || 0) + 1
            
            // 添加到本地点赞记录
            if (res.data && res.data.likeId) {
              this.userLikes.push({
                likeId: res.data.likeId,
                targetId: reply.commentId,
                targetType: 'REPLY',
                userId: this.currentUserId // 使用后端获取的当前用户ID
              })
            }
          } else {
            reply.likes = Math.max(0, (reply.likes || 0) - 1)
            
            // 从本地点赞记录中移除
            const index = this.userLikes.findIndex(like => 
              like.targetId === reply.commentId && like.targetType === 'REPLY'
            )
            if (index !== -1) {
              this.userLikes.splice(index, 1)
            }
          }
        } else {
          this.$message.error(res.message || '操作失败')
        }
        this.submitting = false
      }).catch(err => {
        console.error('操作回复点赞失败:', err)
        this.$message.error('操作失败，请稍后重试')
        this.submitting = false
      })
    },
    
    // 回复评论
    replyToComment(comment) {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再回复')
        return
      }
      
      // 如果点击的是当前已经在回复的评论，则取消回复
      if (this.replyingTo === comment.commentId) {
        this.cancelReply()
        return
      }
      
      // 如果有未提交的回复内容，提示用户
      if (this.replyingTo && this.replyContent.trim() && !confirm('切换回复对象会丢失当前编辑的回复内容，确定继续吗？')) {
        return
      }
      
      // 关闭其他所有可能打开的回复框
      this.comments.forEach(c => {
        if (c.commentId !== comment.commentId && this.replyingTo === c.commentId) {
          // 不再自动取消回复，而是提示用户确认
        }
      })
      
      // 设置当前回复的评论ID和用户ID
      this.replyingTo = comment.commentId
      this.replyToUserId = comment.userId
      this.replyContent = ''
      
      // 滚动到回复框
      this.$nextTick(() => {
        const replyFormElement = document.querySelector(`.comment-item[data-id="${comment.commentId}"] .reply-form`)
        if (replyFormElement) {
          replyFormElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
        }
      })
    },
    
    // 取消回复
    cancelReply() {
      this.replyingTo = null
      this.replyToUserId = null
      this.replyContent = ''
    },
    
    // 提交回复
    submitReply(parentComment) {
      if (!this.replyContent.trim()) {
        this.$message.warning('回复内容不能为空')
        return
      }
      
      // 检查是否包含侮辱性词汇
      if (this.containsInsultingWords(this.replyContent)) {
        this.$message.error('回复内容包含侮辱性词汇，请文明发言')
        return
      }
      
      const reply = {
        postId: this.postId,
        parentId: parentComment.commentId,
        content: this.replyContent.trim(),
        token: localStorage.getItem('token')
      }
      
      this.submitting = true
      
      service.post('/api/forum/comment/addComment', reply).then(res => {
        if (res.code === 200) {
          this.$message.success('回复成功')
          this.cancelReply()
          
          // 保存当前评论的ID，用于重新加载后展开对应评论
          const currentCommentId = parentComment.commentId
          
          // 重新加载评论
          this.getComments()
          
          // 延迟展开刚刚回复的评论的回复区域
          setTimeout(() => {
            const targetComment = this.comments.find(c => c.commentId === currentCommentId)
            if (targetComment) {
              // 展开该评论的回复区域
              Vue.set(targetComment, 'showReplies', true)
              
              // 滚动到该评论的回复区域
              this.$nextTick(() => {
                const repliesContainer = document.querySelector(`.comment-item[data-id="${currentCommentId}"] .comment-replies`)
                if (repliesContainer) {
                  repliesContainer.scrollIntoView({ behavior: 'smooth', block: 'center' })
                }
              })
            }
          }, 800) // 增加延迟确保数据已加载
        } else {
          this.$message.error(res.message || '回复失败')
        }
        this.submitting = false
      }).catch(err => {
        console.error('提交回复失败:', err)
        this.$message.error('回复失败，请稍后重试')
        this.submitting = false
      })
    },
    
    // // 滚动到评论区
    // scrollToComment() {
    //   this.$nextTick(() => {
    //     if (this.$refs.commentSection) {
    //       this.$refs.commentSection.scrollIntoView({ behavior: 'smooth' })
    //     }
    //   })
    // },
    
    // 编辑帖子
    editPost() {
      this.$router.push(`/forum/edit/${this.postId}`)
    },
    
    // 获取分类名称
    getCategoryName(category) {
      const categoryMap = {
        'experience': '经验交流',
        'appreciation': '京剧欣赏',
        'learning': '学习心得',
        'teaching': '教学视频',
        'news': '戏曲动态'
      }
      return categoryMap[category] || category
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知日期'
      
      const date = new Date(dateStr)
      const now = new Date()
      const diff = now - date
      
      // 一小时内显示"x分钟前"
      if (diff < 60 * 60 * 1000) {
        const minutes = Math.floor(diff / (60 * 1000))
        return `${minutes}分钟前`
      }
      
      // 一天内显示"x小时前"
      if (diff < 24 * 60 * 60 * 1000) {
        const hours = Math.floor(diff / (60 * 60 * 1000))
        return `${hours}小时前`
      }
      
      // 一周内显示"x天前"
      if (diff < 7 * 24 * 60 * 60 * 1000) {
        const days = Math.floor(diff / (24 * 60 * 60 * 1000))
        return `${days}天前`
      }
      
      // 其他情况显示完整日期
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },
    
    // 格式化内容（简单处理换行符）
    formatContent(content) {
      if (!content) return ''
      return content.replace(/\n/g, '<br>')
    },
    
    // 切换特定评论的回复显示/隐藏
    toggleCommentReplies(comment, event) {
      // 阻止事件冒泡
      if (event) {
        event.stopPropagation()
      }
      
      // 如果有未提交的回复表单，提示用户
      if (this.replyingTo && this.replyContent.trim() && !confirm('切换显示回复会丢失当前编辑的回复内容，确定继续吗？')) {
        return
      }
      
      // 关闭回复表单
      this.cancelReply()
      
      // 关闭其他所有评论的回复显示
      if (!comment.showReplies) {
        this.comments.forEach(c => {
          if (c.commentId !== comment.commentId && c.showReplies) {
            Vue.set(c, 'showReplies', false)
          }
        })
      }
      
      // 切换当前评论的回复显示状态
      Vue.set(comment, 'showReplies', !comment.showReplies)
    },
    
    // 回复回复
    replyToReply(parentComment, reply) {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再回复')
        return
      }
      
      this.replyingTo = parentComment.id
      this.replyToUserId = reply.userId
      this.replyContent = ''
      
      // 滚动到回复框
      this.$nextTick(() => {
        const replyFormElement = document.querySelector(`.comment-item[data-id="${parentComment.id}"] .reply-form`)
        if (replyFormElement) {
          replyFormElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
        }
      })
    },
    
    // 添加检测侮辱性词汇的方法
    containsInsultingWords(text) {
      if (!text) return false;
      
      // 从导入的函数调用
      return containsInsultingWords(text);
    },
    
    // 添加删除评论方法
    deleteComment(comment) {
      this.$confirm('确定要删除这条评论吗？所有回复也将被删除。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/api/forum/comment/deleteComment/${comment.commentId}`).then(res => {
          if (res.code === 200) {
            this.$message.success('评论已删除');
            // 重新加载评论
            this.getComments();
            this.getPostDetail();
          } else {
            this.$message.error(res.msg || '删除评论失败');
          }
        }).catch(err => {
          console.error('删除评论失败:', err);
          this.$message.error('删除评论失败，请稍后重试');
        });
      }).catch(() => {
        // 用户取消删除操作
      });
    },
    
    // 添加删除回复方法
    deleteReply(comment, reply) {
      console.log(reply);
      this.$confirm('确定要删除这条回复吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/api/forum/comment/deleteComment/${reply.commentId}`).then(res => {
          if (res.code === 200) {
            this.$message.success('回复已删除');
            // 从当前评论的回复列表中移除
            const index = comment.replies.findIndex(r => r.commentId === reply.commentId);
            if (index !== -1) {
              comment.replies.splice(index, 1);
            }
            // 如果没有回复了，更新显示状态
            if (comment.replies.length === 0) {
              this.$set(comment, 'showReplies', false);
            }
          } else {
            this.$message.error(res.msg || '删除回复失败');
          }
        }).catch(err => {
          console.error('删除回复失败:', err);
          this.$message.error('删除回复失败，请稍后重试');
        });
      }).catch(() => {
        // 用户取消删除操作
      });
    },
    
    // 添加获取当前用户ID的方法
    getCurrentUserId() {
      const token = localStorage.getItem('token')
      if (!token) return
      
      service.get(`/api/system/user/getCurrentUser/${token}`).then(res => {
        if (res.code === 200 && res.data) {
          this.currentUserId = res.data.userId || ''
        }
      }).catch(err => {
        console.error('获取当前用户信息失败:', err)
      })
    },
  }
}
</script>

<style scoped>
.post-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  padding-top: 80px;
}

.post-detail {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  transition: all 0.3s ease;
}

.back-link {
  margin-bottom: 20px;
}

.back-link a {
  color: #8B0000;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  font-size: 1rem;
  transition: color 0.3s;
}

.back-link a:hover {
  color: #FFD700;
}

.back-link i {
  margin-right: 5px;
  font-size: 1.1rem;
}

.post-content {
  margin-bottom: 40px;
}

.post-title {
  font-size: 2rem;
  color: #333;
  margin-top: 0;
  margin-bottom: 20px;
  line-height: 1.4;
  font-weight: bold;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.author-info {
  display: flex;
  align-items: center;
}

.author-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
  border: 2px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.author-name {
  font-weight: bold;
  font-size: 1.1rem;
  color: #8B0000;
  margin-bottom: 3px;
}

.author-location {
  font-size: 0.85rem;
  color: #999;
  display: flex;
  align-items: center;
}

.author-location i {
  margin-right: 3px;
}

.publish-time {
  font-size: 0.85rem;
  color: #999;
  margin-top: 3px;
}

.post-stats {
  display: flex;
  gap: 20px;
  font-size: 0.9rem;
  color: #666;
}

.post-stats span {
  display: flex;
  align-items: center;
}

.post-stats i {
  margin-right: 5px;
  font-size: 1.1rem;
}

.likes {
  cursor: pointer;
  transition: all 0.3s;
}

.likes:hover, .likes.is-liked {
  color: #ff4757;
}

.post-tags {
  margin-bottom: 20px;
}

.post-tags .el-tag {
  margin-right: 10px;
  margin-bottom: 8px;
}

.post-topic, .post-type {
  display: flex;
  align-items: center;
  gap: 5px;
}

.post-stats .el-icon-view {
  color: #409EFF; /* 蓝色 */
}

.post-stats .el-icon-chat-dot-round {
  color: #67C23A; /* 绿色 */
}


.post-topic i, .post-type i {
  color: #666;
  font-size: 16px;
}

.fa-heart {
  color: #ff4757; /* 实心心形为红色 */
}

.far.fa-heart:hover {
  color: #ff4757; /* 鼠标悬停时为红色 */
}

.post-info-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  border-left: 3px solid #8B0000;
}

.post-media {
  margin-bottom: 25px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.media-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  overflow: hidden;
  border-radius: 8px;
}

.media-image {
  max-width: 100%;
  max-height: 600px;
  object-fit: contain;
  display: block;
  margin: 0 auto;
}

.video-container {
  position: relative;
  width: 100%;
  background-color: #000;
  border-radius: 8px;
  overflow: hidden;
}

.post-video, .post-audio {
  width: 100%;
  display: block;
}

.post-video {
  max-height: 500px;
}

.audio-container {
  width: 100%;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
  text-align: center;
}

.post-audio {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
}

.post-body {
  line-height: 1.8;
  color: #333;
  font-size: 1.05rem;
  margin-bottom: 30px;
  white-space: pre-wrap;
  word-break: break-word;
}

.post-actions {
  display: flex;
  justify-content: flex-start;
  gap: 15px;
  margin-top: 25px;
}

/* 评论区样式 */
.comment-section {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.section-title {
  color: #8B0000;
  font-size: 1.5rem;
  margin-bottom: 20px;
  position: relative;
  padding-left: 15px;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 20px;
  background-color: #8B0000;
  border-radius: 2px;
}

.comment-form {
  margin-bottom: 30px;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
}

.comment-form:focus-within {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.comment-list {
  margin-top: 20px;
  min-height: 100px;
}

.comments-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  display: flex;
  padding: 20px;
  border-radius: 10px;
  background-color: #fff;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
  isolation: isolate;
  position: relative;
}

.comment-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.comment-avatar, .reply-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 15px;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.reply-avatar {
  width: 40px;
  height: 40px;
}

.comment-avatar img, .reply-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.comment-content, .reply-content {
  flex-grow: 1;
}

.comment-header, .reply-header {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.comment-author, .reply-author {
  font-weight: bold;
  color: #333;
  font-size: 1.05rem;
}

.reply-target {
  color: #8B0000;
  font-weight: 500;
}

.comment-date, .reply-date {
  color: #999;
  font-size: 0.85rem;
  margin-left: auto;
}

.comment-text, .reply-text {
  line-height: 1.6;
  color: #333;
  margin-bottom: 15px;
  word-break: break-word;
  white-space: pre-wrap;
  font-size: 0.95rem;
  letter-spacing: 0.3px;
}

.comment-actions, .reply-actions {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.comment-like, .comment-reply, .reply-like, .reply-reply {
  color: #999;
  font-size: 0.9rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  padding: 5px 10px;
  border-radius: 15px;
}

.comment-like i, .reply-like i, .comment-reply i, .reply-reply i {
  margin-right: 5px;
  font-size: 1.1rem;
}

.comment-like.liked, .reply-like.liked {
  color: #ff4757;
}

.comment-like.liked i, .reply-like.liked i {
  color: #ff4757;
}

.comment-like:hover, .comment-reply:hover,
.reply-like:hover, .reply-reply:hover {
  background-color: rgba(0, 0, 0, 0.05);
  color: #ff4757;
}

.reply-form {
  margin: 15px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 1;
}

.reply-form .form-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.comment-replies-container {
  margin-top: 15px;
}

.replies-toggle {
  cursor: pointer;
  color: #8B0000;
  padding: 8px 12px;
  font-size: 0.9rem;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  border-radius: 4px;
  transition: all 0.3s;
  margin-bottom: 10px;
  background-color: #f9f9f9;
  border: 1px solid #f0f0f0;
  max-width: fit-content; /* 按内容宽度调整大小 */
}

.replies-toggle:hover {
  background-color: #f0f0f0;
  color: #8B0000;
  border-color: #e0e0e0;
}

.replies-toggle i {
  font-size: 0.8rem;
  transition: transform 0.3s ease;
}

.comment-replies {
  margin-top: 5px;
  padding-left: 20px;
  border-left: 2px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  gap: 15px;
  position: relative;
  z-index: 1;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

.reply-item {
  display: flex;
  padding: 15px;
  border-radius: 8px;
  background-color: #f9f9f9;
  transition: all 0.3s ease;
  position: relative;
}

.reply-item:hover {
  background-color: #f5f5f5;
}

.no-comments {
  text-align: center;
  padding: 40px 0;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.no-comments i {
  font-size: 3rem;
  margin-bottom: 15px;
  color: #ddd;
}

.no-comments p {
  font-size: 1.1rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .post-detail-container {
    padding: 10px;
    padding-top: 70px;
  }
  
  .post-detail {
    padding: 20px;
  }
  
  .post-title {
    font-size: 1.6rem;
  }
  
  .post-meta {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .post-stats {
    width: 100%;
    gap: 15px;
    margin-top: 10px;
    justify-content: space-between;
  }
  
  .author-avatar {
    width: 40px;
    height: 40px;
  }
  
  .comment-avatar {
    width: 40px;
    height: 40px;
  }
  
  .reply-avatar {
    width: 30px;
    height: 30px;
  }
  
  .comment-replies {
    padding-left: 10px;
  }
  
  .comment-item {
    padding: 15px;
  }
  
  .reply-item {
    padding: 10px;
  }
  
  .comment-date, .reply-date {
    margin-left: 0;
    width: 100%;
  }
}

@media (max-width: 480px) {
  .post-detail {
    padding: 15px;
  }
  
  .post-title {
    font-size: 1.4rem;
  }
  
  .post-body {
    font-size: 1rem;
  }
  
  .author-avatar {
    width: 35px;
    height: 35px;
    margin-right: 10px;
  }
  
  .author-name {
    font-size: 1rem;
  }
  
  .comment-avatar {
    width: 35px;
    height: 35px;
    margin-right: 10px;
  }
  
  .reply-avatar {
    width: 25px;
    height: 25px;
  }
  
  .comment-actions, .reply-actions {
    justify-content: space-between;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}

.comment-delete,
.reply-delete {
  cursor: pointer;
  color: #999;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  padding: 5px 10px;
  border-radius: 15px;
}

.comment-delete i,
.reply-delete i {
  margin-right: 5px;
  font-size: 1.1rem;
}

.comment-delete:hover,
.reply-delete:hover {
  background-color: rgba(0, 0, 0, 0.05);
  color: #F56C6C;
}
</style> 